/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * bocciawii
 * Copyright (C)  2010 <>
 * 
 * bocciawii is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * bocciawii is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "error-log.h"

using namespace std;

ErrorLog::ErrorLog(string app_name, string app_version, string filename)
{
	//TODO Gestión de errores E/S
	error_log.open((RUTA_LOGS + filename).c_str(), ios::out);
	this->filename = filename;

	time( &tiempo );
	calendario = localtime( &tiempo );

	error_log << app_name 
			  << " versión " 
			  << app_version
			  << " iniciado en: " 
			  << asctime (calendario)
			  << endl;

	error_log << "------------------------------------------------------" 
			  << endl;
	error_log.close();
}


void ErrorLog::log(int tipo, std::string szFormat, ...){

	va_list Arg;
	
	va_start(Arg, szFormat);
	
	//TODO Gestión de errores E/S
	if (!error_log.is_open())
		error_log.open((RUTA_LOGS + filename).c_str(), ios::out | ios::app);
	
	if (error_log.is_open())
	{
		char mensaje[500];
		vsprintf(mensaje, szFormat.c_str(), Arg);
		std::string imprimir;
		imprimir.assign (mensaje);
		if (imprimir.find('\n') != std::string::npos)
			imprimir.erase(imprimir.find('\n'));
		
		switch (tipo)
		{
			case 1: 
				error_log << "ERROR: " << imprimir;
				break;
			case 0:
				error_log << "infor: " << imprimir;
				break;
		}

		
		time ( &tiempo );
		calendario = localtime( &tiempo );
		
		error_log << " - " 
				  << asctime( calendario );
		error_log.close();
	}
	va_end(Arg);
}


ErrorLog::~ErrorLog()
{
	if (!error_log.is_open())
		error_log.open((RUTA_LOGS + filename).c_str(), ios::out | ios::app);
	
	//TODO Gestión de errores E/S
	if (error_log.is_open()){
		time ( &tiempo );
		calendario = localtime( &tiempo );
		
		error_log << endl
				  << "Log finalizado" 
				  << " - "
				  << asctime( calendario )
				  << "******************************************************" 
				  << endl;

		error_log.close();
	}
}
